package pqstorer

//Implements the following interface:
//type UserStorer interface {
//	Save(*User) error
//	Load(string) (*User, error)
//	Exists(string) bool
//	Delete(string) error
//}

import (
	"code.google.com/p/jesus-1496/auth/models"
	"code.google.com/p/jesus-1496/utils/db"
)

type UserStore struct{}

func (p *UserStore) Save(u *models.User) error {
	_, err := db.Exec(`select upsert_user($1::varchar(64),$2::varchar(128),$3::boolean,$4::boolean);`, u.Email, u.HashedPassword, u.IsAdmin, u.IsActive)
	if err != nil {
		return err
	}
	return nil
}

func (p *UserStore) Load(email string) (*models.User, error) {
	var ret models.User
	err := db.UnmarshallQuery(&ret, `select get_user_by_email($1::varchar(64));`, email)
	if err != nil {
		return nil, err
	}
	return &ret, nil
}

func (p *UserStore) Exists(email string) bool {
	var ret bool
	err := db.UnmarshallQuery(&ret, `select user_exists($1::varchar(64));`, email)
	if err != nil {
		logger.Printf("Error during UserStore.Exists(): %v.", err)
	}
	return ret
}

func (p *UserStore) Delete(email string) error {
	db := db.Db()
	_, err := db.Exec(`select delete_user($1::varchar(64));`, email)
	if err != nil {
		return err
	}
	return nil
}

func init() {
	models.SetUserStore(&UserStore{})
}
